package tech.aistar.corejava.day11;

import java.util.LinkedList;
import java.util.Scanner;

/**
 * @Author: lya
 * @Description: 本类的作用描述:括号匹配
 * @CreateDate: 2019/7/29
 * @Version: 1.0
 */
public class BracketDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入括号:");

        String line = sc.nextLine();
        boolean flag = match(line);
        if(flag){
            System.out.println("匹配!");
        }else{
            System.out.println("不匹配!");
        }
    }

    private static boolean match(String line) {
        //1.将字符串转换成字符数组
        char[] arr =  line.toCharArray();

        //2.创建一个LinkedList集合
        LinkedList<Character> list = new LinkedList<>();

        //3.将字符数组中的第一个元素压入栈顶
        list.push(arr[0]);

        //4.从字符数组中的第二个元素开始进行遍历
        for (int i = 1; i < arr.length; i++) {
            //5.永远拿arr[i]和栈顶的元素比较
            Character c1 = null;
            Character c2 = arr[i];
            if(list.isEmpty()){//不存在栈顶元素
                //将当前的c2压入栈顶
                list.push(c2);
                continue;
            }
            //获取栈顶
            c1 = list.getFirst();
            if(c1.equals('(') && c2.equals(')') || c1.equals('[') && c2.equals(']') || c1.equals('{') && c2.equals('}')){
                //弹出栈顶内容
                list.pop();
            }else{
                //将c2压入栈顶
                list.push(c2);
            }
        }
        return list.isEmpty();//如果集合为空说明是匹配
    }
}
